package com.foreknow.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.foreknow.service.BlogService;
import com.google.gson.Gson;
import com.foreknow.entity.Blog;
import com.foreknow.service.BlogService;
import com.foreknow.service.UserService;

@WebServlet({ "/api/blog", "/api/blog-delete", "/api/blog-edit", "/api/randomBlogs", "/api/blogs", "/api/blogs-paging", "/api/blogs-condition",
        "/api/addBlogReadingVolume" })
public class BlogServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private BlogService blogService;
    private UserService userService;
    private Gson gson;
    private Map<String, Object> data;

    public BlogServlet() {
        super();
        blogService = new BlogService();
        userService = new UserService();
        gson = new Gson();
        data = new HashMap<>();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("/api/blog")) {
            String id = request.getParameter("blogId");
            Blog blog = blogService.getBlogById(Integer.valueOf(id));
            if (blog != null) {
                blog.setIsShown(false);
                blog.setBlogUsername(userService.getUserByID(blog.getUserId()).getUsername());
                data.put("errorCode", 0);
                data.put("blog", blog);
                data.put("message", "获取Blog成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "获取Blog失败！");
            }
        } else if (uri.endsWith("/api/randomBlogs")) {
            String category = request.getParameter("categoty");
            Integer pageNum = Integer.valueOf(request.getParameter("pageNum"));
            Integer pageSize = 10;
            Integer limit = (pageNum - 1) * pageSize > 0 ? (pageNum - 1) * pageSize + 1 : 0;
            List<Blog> blogs = null;
            if (category != "" && category != null) {
                System.out.println(category);
                blogs = blogService.getRandomBlogs(limit, pageSize);
            } else {
                blogs = blogService.getRandomBlogs(limit, pageSize);
            }
            if (blogs != null) {
                for (Blog item : blogs) {
                    item.setIsShown(false);
                    item.setBlogUsername(userService.getUserByID(item.getUserId()).getUsername());
                }
                data.put("errorCode", 0);
                data.put("blogs", blogs);
                data.put("message", "获取随机Blog成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "获取随机Blog失败！");
            }

        } else if (uri.endsWith("/api/blogs")) {
            String userId = request.getParameter("userId");
            List<Blog> blogs = blogService.getUserBlogs(Integer.valueOf(userId));
            if (blogs != null) {
                for (Blog item : blogs) {
                    item.setIsShown(false);
                    item.setBlogUsername(userService.getUserByID(item.getUserId()).getUsername());
                }
                data.put("errorCode", 0);
                data.put("blogs", blogs);
                data.put("message", "获取用户Blog成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "获取用户Blog失败！");
            }
        } else if (uri.endsWith("/api/blogs-paging")) {
            Integer userId = Integer.valueOf(request.getParameter("userId"));
            Integer pageNum = Integer.valueOf(request.getParameter("pageNum"));
            Integer pageSize = 2;
            Integer limit = (pageNum - 1) * pageSize > 0 ? (pageNum - 1) * pageSize : 0;
            System.out.println(pageNum + ":" + limit);
            List<Blog> blogs = blogService.getBlogsByUserIdWithPaging(userId, limit, pageSize);
            if (blogs != null) {
                data.put("errorCode", 0);
                data.put("blogs", blogs);
                data.put("message", "获取用户Blog成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "获取用户Blog失败！");
            }
        } else if (uri.endsWith("/api/blogs-condition")) {// 根据queryString查询blog
            String condition = request.getParameter("condition");
            String page = request.getParameter("pageNum");
            Integer pageSize = 5;
            if (page == "" || page == null) {
                List<Blog> blogs = blogService.getBlogsByCondition(condition);
                data.put("errorCode", 0);
                data.put("blogs", blogs);
                data.put("message", "获取Blog成功！");
            } else {
                Integer pageNum = Integer.valueOf(request.getParameter("pageNum"));
                Integer limit = (pageNum - 1) * pageSize > 0 ? (pageNum - 1) * pageSize : 0;
                List<Blog> blogs = blogService.getBlogsByConditionWithPaging(condition, limit, pageSize);
                if (blogs != null) {
                    for (Blog item : blogs) {
                        item.setIsShown(false);
                        item.setBlogUsername(userService.getUserByID(item.getUserId()).getUsername());
                    }
                    data.put("errorCode", 0);
                    data.put("blogs", blogs);
                    data.put("message", "获取Blog成功！");
                } else {
                    data.put("errorCode", -1);
                    data.put("message", "获取用户Blog失败！");
                }
            }
        } else if (uri.endsWith("/api/addBlogReadingVolume")) {
            Integer id = Integer.valueOf(request.getParameter("blogId"));
            Integer volume = blogService.getBlogReadingVolume(id);
            if (volume != -1) {
                if (blogService.addBlogReadingVolume(id, volume + 1)) {
                    data.put("errorCode", 0);
                    data.put("message", "阅读量+1");
                }
            } else {
                data.put("errorCode", -1);
                data.put("message", "数据库操作出错");
            }
        } else if (uri.endsWith("/api/blog-delete")) {
            String id = request.getParameter("blogId");
            if (blogService.deleteBlogById(Integer.valueOf(id))) {
                data.put("errorCode", 0);
                data.put("message", "删除博客成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "删除博客失败！");
            }
        }
        String json = gson.toJson(data);
        response.getWriter().write(json);
        data.clear();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("/api/blog")) {
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            String category = request.getParameter("category");
            String introduction = request.getParameter("introduction");
            String userId = request.getParameter("userId");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String uploadTime = dateFormat.format(new Date());
            Blog blog = new Blog(title, content, uploadTime, Integer.valueOf(userId), category);
            blog.setIntroduction(introduction);
            Integer blogId = blogService.insertBlog(blog);
            if (blogId > 0) {
                data.put("errorCode", 0);
                data.put("blogId", blogId);
                data.put("message", "创建博客成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "创建博客失败！");
            }
        } else if (uri.endsWith("/api/blog-edit")) {
            Integer id = Integer.valueOf(request.getParameter("blogId"));
            String title = request.getParameter("title");
            String content = request.getParameter("content");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String uploadTime = dateFormat.format(new Date());
            String category = request.getParameter("category");
            Blog blog = new Blog(title, content, uploadTime, null, category);
            blog.setId(id);
            if (blogService.updateBlog(blog)) {
                data.put("errorCode", 0);
                data.put("message", "修改成功！");
            } else {
                data.put("errorCode", -1);
                data.put("message", "修改失败！");
            }
        }
        String json = gson.toJson(data);
        response.getWriter().write(json);
        data.clear();
    }
}
